package start.spring.basic.util.common;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import ch.qos.logback.core.PropertyDefinerBase;

/**
 * 
 * ****************************************************************************
 * 获取spring boot启动端口
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2021年1月27日
 ******************************************************************************
 */
public class LoggerFilePort extends PropertyDefinerBase {

	private final static String PORT_KEY = "server.port";
	
	private final String BOOTSTRAP_FILE = "bootstrap.properties";
	
	private final String APPLICATION_FILE = "application.properties";
	
	private final String PORT_DEFAULT = "8080";
	
	private static String port = "";
	
	private static String commandPort;
	
	@Override
	public String getPropertyValue() {
		return getPort();
	}
	
	public static void getCommandPort(String[] args) {
		if(args!=null&&args.length>0) {
			for(String arg:args) {
				if(arg.indexOf(PORT_KEY)>0) {
					commandPort = arg.substring(arg.indexOf(PORT_KEY) + PORT_KEY.length() + 1).trim();
				}
			}
		}
	}

	private String getPort() {
		if(StringUtil.isEmpty(port)) {
			//优先获取系统变量
			String sysPort = System.getProperty(PORT_KEY);
			if(!StringUtil.isEmpty(sysPort)) {
				port = sysPort;
			}else if(!StringUtil.isEmpty(commandPort)){
				//获取启动命令行设置参数
				port = commandPort;
			}else{
				//获取bootstrap.properties文件中设置的端口
				Map<String, String> properties = this.loadSysFile(BOOTSTRAP_FILE);
				if(properties!=null&&properties.containsKey(PORT_KEY)&&
						!StringUtil.isEmpty(properties.get(PORT_KEY))) {
					port = properties.get(PORT_KEY);
				}else {
					//获取application.properties文件中设置的端口
					properties = this.loadSysFile(APPLICATION_FILE);
					if(properties!=null&&properties.containsKey(PORT_KEY)&&
							!StringUtil.isEmpty(properties.get(PORT_KEY))) {
						port = properties.get(PORT_KEY);
					}else {
						//默认端口
						port = PORT_DEFAULT;
					}
				}
			}
		}
		return port;
	}
	
	/**
	 * 读取系统属性文件
	 *	
	 * @param fileName
	 * @return
	 * @since           1.0
	 */
	private Map<String, String> loadSysFile(String fileName) {
		Map<String, String> propertiesMap = new HashMap<>();
		
		try {
			Properties properties = PropertiesLoaderUtils.loadAllProperties(fileName);
			
			propertiesMap = new HashMap<String, String>();
	        for (Object key:properties.keySet()) {
	            String keyStr = key.toString();
	            propertiesMap.put(keyStr, new String(properties.getProperty(keyStr).getBytes("ISO-8859-1"),"utf-8"));
	        }
	        
		} catch (Exception e) {
			
		}
		return propertiesMap;
	}
	
}
